from Logs.logs import forge_logger
from requests import request
import random
from typing import Union
import os
import json
from request_tracking_interface import build_request_query


class UserManage:
    def __init__(self):
        self.code_url = 'http://124.220.33.63:8700/sms/login/send'
        self.login_url = 'http://124.220.33.63:8700/login/phone'
        self.header = {
            "Content-Type": "application/json"
        }
        self.write_json_data = []

    def new_user_enroll(self, phone: Union[str, int]) -> dict:
        json_data = {"To": phone}
        code_response = request(method="POST", url=self.code_url, json=json_data).json()
        forge_logger.info(f"发送验证码响应为{code_response}")
        code = code_response.get("data").get("Code")
        forge_logger.success(f"发送验证码成功，验证码为{code}")
        login_data = {
            "Phone": phone,
            "PhoneCode": code
        }
        login_response = request("post", url=self.login_url, headers=self.header, json=login_data).json()
        forge_logger.info(f"用户注册响应为{login_response}")
        token, self_id = login_response.get("data")[0].get("Token"), login_response.get("data")[0].get("ID")
        forge_logger.info(f"用户注册成功，phone为{phone},ID为{self_id},token为{token}")
        return {"token": token, "id": self_id, "phone": phone}

    @staticmethod
    def generate_phone_number():
        # 第一位固定为1
        first_digit = '1'
        # 第二位在3到9之间随机选择
        second_digit = "888888"
        # 剩下的4位数字在0-9中随机生成
        remaining_digits = ''.join([str(random.randint(0, 9)) for _ in range(4)])

        # 组合生成的电话号码
        phone_number = first_digit + second_digit + remaining_digits
        return f"+86{phone_number}"

    def write_dict_to_json(self):
        # forge_logger.info(f"写入数据为{data}")
        current_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd()
        # 拼接完整的文件路径
        file_path = os.path.join(current_dir, "JsonData", "is_match_user.json")
        # file_path = os.path.join(os.path.dirname(__file__), "JsonData", "is_match_user.json")
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        data.get("data").extend(self.write_json_data)
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)

    @staticmethod
    def edit_user_info(data):
        headers = {
            "Authorization": f"Bearer {data.get('token')}"
        }
        url = "http://124.220.33.63:8700/user/info"
        json_data = {"nickname": f"suki{random.randint(1000, 9999)}", "sex": 0, "birthday": "", "avatar": ""}
        response = request("patch", url=url, headers=headers, json=json_data).json()
        forge_logger.success(f"修改用户信息响应为{response}")

    @staticmethod
    def is_match(data):
        headers = {
            "Authorization": f"Bearer {data.get('token')}"
        }
        info_url = "http://124.220.33.63:8700/user/info"
        info_response = request("get", url=info_url, headers=headers, params=build_request_query()).json()
        forge_logger.info(f"用户信息响应为{info_response}")
        UserManage.edit_user_info(data)
        if info_response.get("data").get("MatchID") == 0:
            forge_logger.success(f"phone:{data.get('phone')}用户未匹配,可以进行匹配")
            return info_response.get("data").get("MatchCode")
        else:
            forge_logger.warning(f"phone:{data.get('phone')}用户已匹配，无法进行匹配")
            return False

    def user_match(self, phone: Union[str, int], match_phone: Union[str, int]):
        data1 = self.new_user_enroll(phone)
        data2 = self.new_user_enroll(match_phone)
        data1_match_id = UserManage.is_match(data1)
        data2_match_id = UserManage.is_match(data2)
        if data1_match_id and data2_match_id:
            headers = {
                "Authorization": f"Bearer {data1.get('token')}"
            }
            params = build_request_query(code=data2_match_id)
            match_url = f"http://124.220.33.63:8700/match/info"
            match_response = request("post", headers=headers, url=match_url, params=params).json()
            # forge_logger.debug(f"{str(headers)},{match_url},{data2_match_id}")
            forge_logger.info(f"匹配响应为{match_response}")
            data = {"self_data": data1, "match_data": data2}
            self.write_json_data.append(data)


if __name__ == '__main__':
    user = UserManage()
    # user.new_user_enroll('18888888889')
    # user.user_match('+8618888888787', '+8618888888778')
    # user.user_match('+8618888888778', '+8618888888777')
    # user.write_dict_to_json()
    phone_list = [user.generate_phone_number() for i in range(50)]
    for i in range(0, len(phone_list) - 1, 2):
        user.user_match(phone_list[i], phone_list[i + 1])
    user.write_dict_to_json()